package net.sf.rose.jdbc;

import org.apache.commons.lang.StringUtils;

/**
 * 功能：日志处理
 * 
 * @author fengjian
 * @since 2013/05/18
 */
public class GenericLog4j implements GenericLog {

	/**
	 * 拼装SQL日志语句
	 */
	public String getLog(GenericDAO dao, QuerySQL query) {
		String sql = query.getSql();
		java.util.List<Object> list = query.getParameterList();
		if (list == null || list.size() == 0) {
			return sql;
		}
		if (list.get(0) instanceof Object[]) {
			return getBatchLog(sql, list, query);
		}
		for (Object obj : list) {
			if (obj == null) {
				sql = StringUtils.replaceOnce(sql, "?", "null");
			} else {
				sql = StringUtils.replaceOnce(sql, "?", obj.toString());
			}
		}
		sql = " sql: " + sql;
		UserBean user = query.getUser();
		return user != null ? "username:" + user.getUserName() + sql : sql;
	}

	/**
	 * 拼装SQL日志语句(包括null)
	 */
	public String getLogAll(GenericDAO dao, QuerySQL query) {
		String sql = query.getSql();
		java.util.List<Object> list = query.getParameterList();
		if (list == null || list.size() == 0) {
			return sql;
		}
		String val = null;
		for (Object obj : list) {
			if (obj == null) {
				val = "null";
			} else {
				val = obj.toString();
			}
			sql = StringUtils.replaceOnce(sql, "?", val);
		}
		sql = " sql: " + sql;
		UserBean user = query.getUser();
		return user != null ? "username:" + user.getUserName() + sql : sql;
	}

	/**
	 * 拼装SQL批处理日志语句
	 */
	private String getBatchLog(String sql, java.util.List<Object> list, QuerySQL query) {
		if (list == null || list.size() == 0) {
			return sql;
		}
		int index;
		StringBuffer buffer = null;
		StringBuffer logBuf = new StringBuffer();
		for (Object obj : list) {
			Object[] arr = (Object[]) obj;
			buffer = new StringBuffer(sql);
			for (int i = 0; i < arr.length; i++) {
				index = buffer.indexOf("?");
				buffer.replace(index, index + 1, arr[i].toString());
			}
			logBuf.append(buffer.toString()).append("\n");
		}
		sql = " sql: " + logBuf.toString();
		UserBean user = query.getUser();
		return user != null ? "username:" + user.getUserName() + sql : sql;
	}

}
